package com.carnation._unsafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * <p>
 * sum.misc.Unsafe示例
 *
 * 使用场景：
 * 1：Netty使用Unsafe的内存操作API提高效率
 * 2：DirectByteBuffer操作堆外内存使用Unsafe提供的堆外内存API。
 * 3：java.util.concurrent.lock.LockSupport使用Unsafe的park和unpark
 * 4：java.util.concurrent.atomic下的原子类
 *
 * </p>
 *
 * @author: Sunny
 * @date: 2021/1/29
 * @version: v1.0.0
 */
public class UnsafeTest {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        System.out.println(reflectGetUnsafe());
    }

    /**
     * 通过反射获取Unsafe类
     * @return
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     */
    private static Unsafe reflectGetUnsafe() throws NoSuchFieldException, IllegalAccessException {
        Field field  = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        return (Unsafe) field.get(null);
    }

}
